<?php
if (!defined('CORE')) exit('Request Error!');

/**
 * 主入口
 */
class ctl_index
{
    //分类数组
    private static $type_arr = array();

    private static function init()
    {
        $res_type = db::get_all("SELECT * FROM `book_tag` WHERE `id` < 100");
        if($res_type) foreach ($res_type as $k=>$v)
        {
            self::$type_arr[$v['id']] = $v['name'];
        }
    }

    function __construct(){ }

    /**
     * index
     * 
     * @return void
     */
    //首页
    public function index()
    {
//       /**/echo "你好世界";exit;
        $lists = array();
        if(isset($_SESSION['id']) && $_SESSION['id'] != "")
        {
            $id = $_SESSION['id'];
            $lists = db::get_one("SELECT * FROM `user` WHERE `id` ='{$id}'");
        }
        else
        {
            $lists['headimgurl'] = "static/images/wx_person_ico.png";
        }
        tpl::assign("v1",$lists);
        tpl::display('index.tpl');
    }

    //搜索
    public function search()
    {
        tpl::display('search.tpl');
    }

    //异步搜索
    public function ajax_search()
    {
        self::init();
        $res = array('errcode'=>'1','msg'=>'invalid keyword');
        $book_name = req::item('book_name');
        $list = db::get_all("SELECT * FROM book WHERE `book_name` LIKE '%{$book_name}%' ORDER BY id DESC limit 10");
        if($list)
        {
            foreach($list as $k=>$v){
                $list[$k]['url']        = '?ct=index&ac=book&id=' . $v['id'];
                $list[$k]['img']        = empty($v['img']) ? 'static/images/wanghong.jpg' : $v['img'];
                $list[$k]['book_type']  = empty($v['book_type'])?"暂未分类":self::$type_arr[$v['book_type']];
                $list[$k]['author']     = empty($v['author']) ? '暂无作者' : $v['author'];
                $list[$k]['remark']     = empty($v['remark']) ? '暂无描述' : $v['remark'];
                $list[$k]['book_tag']   = empty($v['book_tag']) ? '暂无' : $v['book_tag'];
            }

            $res['errcode'] = 0;
            $res['msg'] = 0;
            $res['list']  =$list;
            exit(json_encode($res));
        }
        else
        {
            $res['msg'] = '没有数据';
            exit(json_encode($res));
        }
    }

    //异步书籍详情
    public function ajax_index()
    {
        $res = array('errcode'=>'1','msg'=>'invalid type');
        $book_type = req::item('type', '', 0);

        $list = db::get_all("SELECT id,book_name,remark,img FROM book where book_type='{$book_type}' limit 3");
        if($list)
        {
            foreach($list as $k=>$v)
            {
                $list[$k]['url'] = '?ct=index&ac=book&id=' . $v['id'];
                $list[$k]['img'] = empty($v['img']) ? 'static/images/psbasd.jpg' : $v['img'];
                $list[$k]['remark'] = empty($v['remark']) ? '暂无描述' : $v['remark'];
                $list[$k]['book_tag'] = empty($v['book_tag']) ? '暂无' : $v['book_tag'];
                $list[$k]['author'] = empty($v['author']) ? '暂无作者' : $v['author'];
                $list[$k]['mini_img'] = !isset($v['mini_img']) ? 'http://'.$_SERVER['HTTP_HOST'].'/static/images/73916d1.jpg' : $v['mini_img'];

                $arr = explode("." , $v['book_name']);
                $list[$k]['book_name'] = $arr[0];
            }
            $res['errcode'] = 0;
            $res['msg'] = 'ok';
            $res['list'] = $list;
        }
        else
        {
            $res['errcode'] = 0;
            $res['msg'] = 'ok';
            $res['list'] = array();
        }

        exit(json_encode($res));
    }

    //首页轮播图
    public function ajax_banner()
    {
        $res = array('errcode'=>'1','msg'=>'invalid type');
        $book_type = req::item('type', '', 0);

        $list = db::get_all("SELECT id,book_name,remark,img FROM book where book_type='{$book_type}' limit 3");
        if($list)
        {
            foreach($list as $k=>$v)
            {
                $list[$k]['img'] = empty($v['img']) ? 'static/images/14649164775591236_700_240.jpg' : $v['img'];
                $list[$k]['url'] = '?ct=index&ac=book&id=' . $v['id'];
                $list[$k]['remark'] = empty($v['remark']) ? '暂无描述' : $v['remark'];
                $list[$k]['book_tag'] = empty($v['book_tag']) ? '暂无' : $v['book_tag'];
                $list[$k]['mini_img'] = !isset($v['mini_img']) ? 'http://'.$_SERVER['HTTP_HOST'].'/static/images/73916d1.jpg' : $v['mini_img'];
            }
            $res['errcode'] = 0;
            $res['msg'] = 'ok';
            $res['list'] = $list;
        }
        else{
            $res['errcode'] = 0;
            $res['msg'] = 'ok';
            $res['list'] = array();
        }

        exit(json_encode($res));
    }

    //书籍详情页
    public function book()
    {

        self::init();
        $id = req::item("id");
        $row =  db::get_one("SELECT * FROM `book` WHERE `id`='{$id}'");
        $row['img'] = empty($row['img']) ? 'static/images/wanghong.jpg' : $row['img'];
        $arr = explode("." , $row['book_name']);
        $row['book_name'] = $arr[0];
        $row['book_type'] = empty($row['book_type'])?"主编推荐":self::$type_arr[$row['book_type']];
        $row['author'] = empty($row['author'])?"最好的编辑":$row['author'];
        $row['remark'] = empty($row['remark'])?"暂时是空的空的空的空空空空空空空空空空空空空":$row['remark'];

        $data = db::get_all("SELECT * FROM `book_chapter` WHERE `book_id` ='{$id}' limit 4");
        $read_now = db::get_one("SELECT min(id) AS id  FROM `book_chapter` WHERE `book_id` ='{$id}'");
        $read_now ="?ct=index&ac=reading&id={$id}&chapter_id={$read_now['id']}";

        tpl::assign('v',$row);
        tpl::assign('data',$data);
        tpl::assign('read_now',$read_now);
        tpl::display('book.tpl');
    }

    //显示全部章节
    public function all_chapter()
    {
        $id = req::item("id");
        $data = db::get_all("SELECT * FROM `book_chapter` WHERE `book_id` ='{$id}'");
        $list = db::get_one("SELECT * FROM `book` WHERE `id`='{$id}'");
        $arr = explode("." , $list['book_name']);
        $list['book_name'] = $arr[0];

        tpl::assign("data",$data);
        tpl::assign("v",$list);
        tpl::display("all.chapter.tpl");
    }

    //搜索详情页
    public function reading()
    {
        $id = req::item('id',0,'int');
        $page = req::item('page',1);
        $chapter_id = req::item('chapter_id',1);

        if($id)
        {
            $info = db::get_one("select * from book where id='{$id}'");
            //阅读pdf文件
            if($info['book_suffix']=='pdf')
            {
                //echo 1;
                //tpl::display('reading_pdf.tpl');
                $k = $info['down_path'];
                $info['down_path'] = iconv('utf-8','GBK',$info['down_path']);//使用utf8是错误的,中文的需要转一下
                if(!file_exists(PATH_UPLOADS.$info['down_path']))
                {
                    exit('file not exists');
                }
                //方法一
                ///tpl::display('reading_flex1.tpl');
                ///exit;
//echo 'http://up.book.com/static'.$k;
                //方法二
                //header('Content-type: application/pdf');
                //header('filename='.PATH_UPLOADS.$info['down_path']);
                echo '<embed width=100% height=100% fullscreen=yes src="http://up.book.com'.$k.'" />';
                exit;
            }
            elseif($info['book_suffix']=='mobi')
            {

            }
            elseif($info['book_suffix']=='txt')
            {
                //阅读txt文件
                if($info['is_chapter']==0)//没有设计章节就默认使用字数
                {
                    $info['down_path'] = iconv('utf-8','GBK',$info['down_path']);//使用utf8是错误的,中文的需要转一下
                    if($info['down_path'] && file_exists(PATH_UPLOADS.$info['down_path']))
                    {

                        $html =  file_get_contents(PATH_UPLOADS.$info['down_path']);
                        //判断内容是否utf8
                        $istype = self::TestUtf8($html);

                        if($istype==1)
                        {
                            $html = iconv('GBK','utf-8',$html);
                        }
                        elseif($istype==0)
                        {
                            $html = iconv('GBK','utf-8',$html);
                        }elseif($istype==2){
                            //utf8,不用转换
                        }

                        $length=strlen($html);
                        $page_count=ceil($length/2000);
                        //------------截取中文字符串---------
                        ///$c=self::_msubstr($html,0,($page-1)*2000);
                        ///$c1=self::_msubstr($html,0,$page*2000);
                        ///$exec_html = substr($c1,strlen($c),strlen($c1)-strlen($c));
                        $s = ($page-1)*2000;
                        $e = 2000;
                        $info['body'] = self::_strcut($html,$s,$e);
                        $info['pages_p'] =$page<2?'':'<a class=\'bc_gray mgb_r\' href=index.php?ac=reading&id='.$id.'&page='.($page-1).'>上一页</a>';
                        $info['pages_n'] ='<a class=\'bc_gray mgb_r\' href=index.php?ac=reading&id='.$id.'&page='.($page+1).'>下一页</a>';
                        $info['title_p'] ='<a class=\'font_g\' href=index.php?ac=book&id='.$id.'>'.$info['book_name'].'</a>';
                        $info['title_p1'] ='<a class=\'font_g\' href=index.php?ac=book&id='.$id.'>'.'返回作品首页'.'</a>';
                        $info['chapter_p'] ='';//&nbsp; &gt; &nbsp;  跳转到章节的url。这里为空
                        $info['chapter_p1'] ='';//&nbsp; &gt; &nbsp;  跳转到章节的url。这里为空
                    }
                    else
                    {
                        die('book not exists');
                    }
                }
                else //使用章节
                {
                    $chapter_info = db::get_one("select * from book_chapter where id =$chapter_id");
                    $info['down_path'] = iconv('utf-8','GBK',$info['down_path']);//使用utf8是错误的,中文的需要转一下
                    if($info['down_path'] && file_exists(PATH_UPLOADS.$info['down_path']) && $chapter_info)
                    {
                        $info['body'] ='';
                        $hide=0;
                        $i=0;
                        $handle = @fopen(PATH_UPLOADS . $info['down_path'], "r");
                        if ($handle) {

                            $insertdb = array();
                            while (!feof($handle)) {

                                $buffer = fgets($handle, 4096);
                                if($i>=$chapter_info['start_rows'] && $i<=$chapter_info['end_rows'])
                                {
                                    $info['body'] .= $buffer;
                                }

                                $i++;
                                if($i > $chapter_info['end_rows']+1) break;
                            }
                            fclose($handle);
                            if($chapter_info['end_rows']+1 ==$i){
                                $hide=1;
                            }
                        }

                        $info['body'] ;
                        $info['pages_p'] =$chapter_info['start_rows']<3?'':'<a class=\'bc_gray mgb_r\' href=index.php?ac=reading&id='.$id.'&chapter_id='.($chapter_id-1).'>上一章</a>';
                        $info['pages_n'] =$hide?'':'<a class=\'bc_gray mgb_r\' href=index.php?ac=reading&id='.$id.'&chapter_id='.($chapter_id+1).'>下一章</a>';
                        $info['title_p'] ='<a class=\'font_g\' href=index.php?ac=book&id='.$id.'>'.$info['book_name'].'</a>';
                        $info['title_p1'] ='<a class=\'font_g\' href=index.php?ac=book&id='.$id.'>'.'返回作品首页'.'</a>';
                        $info['chapter_p'] ='';//&nbsp; &gt; &nbsp;  跳转到章节的url。这里为空
                        $info['chapter_p1'] ='';//&nbsp; &gt; &nbsp;  跳转到章节的url。这里为空
                    }
                    else
                    {
                        die('book|chapter_info  not exists');
                    }


                }

            }
            else
            {
                die('未知文件后缀');
            }

        }else{
            die('id null');
        }
        tpl::assign('v',$info);

        tpl::display('reading.tpl');
    }

    //推荐书籍
    public function like()
    {
        $arr = array();
        $id = req::item("id");
        $row = db::get_one("SELECT * FROM `book` WHERE `id` ='{$id}'");
        $list = db::get_all("SELECT * FROM `book` WHERE `book_type` = '{$row['book_type']}' AND `id` !='{$id}' limit 3");

        if($list) foreach ($list as $k=>$v)
        {
            $like[$k]['img'] = empty($v['img']) ? 'static/images/psbasd.jpg' : $v['img'];
            $arr = explode("." , $v['book_name']);
            $like[$k]['book_name'] = $arr[0];
            $like[$k]['url'] = '?ct=index&ac=book&id=' . $v['id'];
        }

        exit(json_encode($like));
    }

    //章节
    public function chapter()
    {
        $id = req::item('id',0,'int');


        tpl::display('chapter.tpl');
    }

    //精选推荐
    public function choice_files()
    {
        $id = req::item("id");
        $book_tag = $list =array();
        $files = db::get_all("SELECT * FROM `book` WHERE `book_type` = '{$id}' limit 15");

        if($files) foreach ($files as $k=> &$v)
        {
            $arr = explode("." , $v['book_name']);
            $list[$k]['book_name'] = $arr[0];
            $list[$k]['url']        = '?ct=index&ac=book&id=' . $v['id'];
            $list[$k]['img']        = empty($v['img']) ? 'static/images/wanghong.jpg' : $v['img'];
            $list[$k]['author']     = empty($v['author']) ? '暂无作者' : $v['author'];
            $list[$k]['remark']     = empty($v['remark']) ? '暂无描述' : $v['remark'];
            $book_tag['book_tag'] = empty($v['book_tag']) ? array():explode(',',$v['book_tag']);
        }


        tpl::assign("list",$list);
        tpl::assign("book_tag",$book_tag);
        tpl::display('choice.files.tpl');
    }

    // 后台设置，自动生个章节
    public function create_chapter()
    {
        $id = req::item('id',0,'int');
        $info = db::get_one("select * from book where id='{$id}'");
        $info['down_path'] = iconv('utf-8','GBK',$info['down_path']);//使用utf8是错误的,中文的需要转一下
        if($info['is_chapter']==1) {
            die('已有章节不能再生成');
        }
        if($info['down_path'] && file_exists(PATH_UPLOADS.$info['down_path']))
        {
            $handle = @fopen(PATH_UPLOADS . $info['down_path'], "r");
            if ($handle) {
                $i=0;
                $insertdb = array();
                while (!feof($handle)) {
                    $buffer = fgets($handle, 1024);
                    $buffer = substr($buffer,0,20);
                    preg_match_all("/(第.*?章)/", $buffer, $out);
                    if(isset($out[1][0]))
                    {
                        $insertdb[$i]['id'] = $id;
                        $insertdb[$i]['chapter'] = $out[1][0];
                        $insertdb[$i]['start_rows'] = $i;
                        if(isset($findit)){
                           $insertdb[$findit]['end_rows'] = $i-1;
                        }
                        $findit = $i;
                    }
                    $i++;
//
                }

                if(isset($findit)){
                    $insertdb[$findit]['end_rows'] = $i-1;
                }

                fclose($handle);
            }
            if($insertdb)
            {
                $sql='';
                foreach($insertdb as $k=>$v)
                {
                    $sql .= "('".implode("','",$v)."'),";
                }
                $sql = rtrim( $sql,',');

                //print_r("insert into book_chapter (`id`,`chapter`,`start_rows`,`end_rows`) values $sql");
                db::query("insert into book_chapter (`book_id`,`chapter`,`start_rows`,`end_rows`) values $sql");
                db::update('book', array('is_chapter' => 1), 'id=' . $id);
                echo '成功';
            }
        }
        else
        {
            die('in null');
        }
    }

    //接收用户查询的 关键字
    public static function search1()
    {
        $keyword = trim(req::item('keyword', ''));
        $rtype = req::item('rtype','html');
        if (!$keyword)
        {
            $sql = "SELECT word FROM `search_words` ORDER BY num DESC,addtime DESC LIMIT 8";
            $words = db::get_all($sql);
            if (!$words)
            {
                $words = array();
            }
            $record = mod_community::getcookie('search_record');
            if ($record)
            {
                $record = explode(',', $record);
            }
            tpl::assign('record', $record);
            tpl::assign('words', $words);
            tpl::display('search.tpl');
            exit();
        }

        $rows_local = array();
        $local = db::get_all("select book_id,book_name from book where book_name like '%{$keyword}%'");
        if($local)foreach($local as $k=>$v)
        {
            $rows_local[$v['book_id']] = array(
                'title' =>$v['book_name'],
                'url' =>'?ct=index&ac=receiv_choose&book_id='.$v['book_id'].'&title='.$v['book_name'],
                'book_id' =>$v['book_id'],

            );
        }
        //查找本地数据库
        //查找其他网络
        $rows = self::_get_ansy_search($keyword);
        $rows_new = array();

        if($rows)foreach($rows as $k=>$v)
        {
            if(!isset($rows_local[$v['id']]))//如果本地有的，就不显示网络上的书籍
                $rows_new[] = array(
                    'title' =>$v['title'],
                    'url' =>'?ct=index&ac=receiv_choose&book_id='.$v['id'].'&title='.$v['title'],
                    'book_id' =>$v['id'],

                );
        }

        tpl::assign('rows_local', $rows_local);
        tpl::assign('rows', $rows_new);
        tpl::display('search.tpl');
        exit();

        /*if($rtype=='json') echo json_encode($list);
        else print_r($list);*/

    }

    //接收用户选中的的id+bookname, 那么用户需要看到一篇文章的列表页面（目前需要）
    public static function receiv_choose()
    {

        $book_id = (int)req::item('book_id','0');
        $title = trim(req::item('title',''));
        $title = str_replace(array('/',"\\",':','*','?','<','>','|'),'',$title);
        if(!$book_id or !$title)
        {
            exit('html：id title null');
        }
        $book_id = $book_id;//-998;
        $_SESSION[$title] = $book_id;//中文变量需要处理一下：三体3：死神永生-刘慈欣.mobi=》

        //$id = $id -998;//唯一
        ///require_once './core/init.php';
        ///$exists = db::get_one("select * from book where down_url=1 and (book_id='{$id}' or book_name like'%{$title}%')");
        $exists = db::get_one("select * from book where is_down=1 and book_id='{$book_id}'");
        $issend = $issave1 = $isdown1 = 0 ;

        if(!$exists)
        {
            $issend = self::_call_send_email($book_id);//$issend =1;
            ///$issend=1;
            if($issend==1)
            {
                //把邮件的信息记录到表

                $issave1 =  self::save_record_fordb();///var_dump($issave1);exit;

                //从表的记录下载附件,保存文件，并修改记录
                $isdown1 = self::down_book_url();
            }
            else
            {
                die('没有请求发送附件');
                //echo  -10010;//找到文件，对否发送附件失败。
                //exit;
                //file_put_contents(PATH_ROOT.'/log.txt',"用户点击(id={$id},title={$title}),发送标识={$issend}",FILE_APPEND);
            }

            $exists = db::get_one("select * from book where is_down=1 and book_id='{$book_id}'");
        }
        $e1 = count($exists);
        file_put_contents(PATH_ROOT.'/log.txt',"是否存在={$e1}用户点击(id={$book_id},title={$title}),发送标识={$issend},是否保存数据库={$issave1},是否下载={$isdown1}\r\n",FILE_APPEND);


        $html = PATH_UPLOADS.$exists['down_path'];
        $exists['down_path'] = iconv('utf-8','GBK',$exists['down_path']); //使用utf8是错误的,中文的需要转一下
        if(file_exists(PATH_UPLOADS.$exists['down_path']))
        {
            //$html =  file_get_contents($exists['down_path']);//有没有将MOBI文件转换成txt的快捷方法 这里？http://www.convertfiles.com/convert/ebook/MOBI-to-TXT.html
            //或者试试mobi2oeb
            //这里应该显示一个列表

            $_SESSION['reading_id'] = $exists['id'];

            header("Location: index.php?ct=index&ac=reading&id");
            exit;
        }
        //
        die('同步失败');
        header('Location: ' . $_SERVER['HTTP_REFERER']);


        echo $html;

    }

    //开始读取文章
    public static function reading1()
    {
        $id = req::item('id',null);
        $page = req::item('page',1);
        $page = max(1,$page);
        if(!$id) $id = $_SESSION['reading_id'];


        $exists = db::get_one("select * from book where id='{$id}'");

        $exists['down_path'] = iconv('utf-8','GBK',$exists['down_path']);//使用utf8是错误的,中文的需要转一下
        if($exists['down_path'] && file_exists(PATH_UPLOADS.$exists['down_path']))
        {

            $html =  file_get_contents(PATH_UPLOADS.$exists['down_path']);
            //判断内容是否utf8
            $istype = self::TestUtf8($html);

            if($istype==1)
            {
                $html = iconv('GBK','utf-8',$html);
            }
            elseif($istype==0)
            {
                $html = iconv('GBK','utf-8',$html);
            }elseif($istype==2){
                //utf8,不用转换
            }



            $length=strlen($html);
            $page_count=ceil($length/2000);
            //------------截取中文字符串---------
            ///$c=self::_msubstr($html,0,($page-1)*2000);
            ///$c1=self::_msubstr($html,0,$page*2000);
            ///$exec_html = substr($c1,strlen($c),strlen($c1)-strlen($c));
            $s = ($page-1)*2000;
            $e = 2000;
            $exec_html = self::_strcut($html,$s,$e);

            $pagehtml ='<a href=index.php?ct=index&ac=reading&id&page='.($page-1).'>上一页</a>
                        <a href=index.php?ct=index&ac=reading&id&page='.($page+1).'>下一页</a>
            ';

        }
        else
        {
            die('参数有误');
        }

        tpl::assign('html',$exec_html);
        tpl::assign('title',$exists['book_name']);
        tpl::assign('pagehtml',$pagehtml);
        tpl::display('reading.tpl');

    }

    //暂无
    private static function _msubstr($str,$start,$len)
    {
        $strlength=$start+$len;
        $tmpstr="";
        for($i=0;$i<$strlength;$i++)
        {
            if(ord(substr($str,$i,1))==0x0a)
            {
                $tmpstr.='';//'<br />';
            }

            if(ord(substr($str,$i,1))>0xa0)
            {
                $tmpstr.=substr($str,$i,2);
                $i++;
            }
            else
            {
                $tmpstr.=substr($str,$i,1);
            }
        }
        return $tmpstr;
    }
    //在用
    private static function _strcut($str,$start,$len){
        if($start < 0)
            $start = strlen($str)+$start;

        $retstart = $start+ self::_getOfFirstIndex($str,$start);
        //echo $retstart;
        $retend = $start + $len -1 + self::_getOfFirstIndex($str,$start + $len);
        //echo $retend;
        return substr($str,$retstart,$retend-$retstart+1);
    }
    //判断字符开始的位置
    private static function _getOfFirstIndex($str,$start){
        $char_aci = ord(substr($str,$start-1,1));
        if(223<$char_aci && $char_aci<240)
            return -1;
        $char_aci = ord(substr($str,$start-2,1));
        if(223<$char_aci && $char_aci<240)
            return -2;
        return 0;
    }
    //返回 1 表示纯 ASCII(即是所有字符都不大于127)
    //返回 2 表示UTF8
    //返回 0 表示正常gb编码
    private static function TestUtf8($text)
    {
        if(strlen($text) < 3) return false;
        $lastch = 0;
        $begin = 0;
        $BOM = true;
        $BOMchs = array(0xEF, 0xBB, 0xBF);
        $good = 0;
        $bad = 0;
        $notAscii = 0;
        for($i=0; $i < strlen($text); $i++)
        {
            $ch = ord($text[$i]);
            if($begin < 3)
            {
                $BOM = ($BOMchs[$begin]==$ch);
                $begin += 1;
                continue;
            }

            if($begin==4 && $BOM) break;

            if($ch >= 0x80 ) $notAscii++;

            if( ($ch&0xC0) == 0x80 )
            {
                if( ($lastch&0xC0) == 0xC0 )
                {
                    $good += 1;
                }
                else if( ($lastch&0x80) == 0 )
                {
                    $bad += 1;
                }
            }
            else if( ($lastch&0xC0) == 0xC0 )
            {
                $bad += 1;
            }
            $lastch = $ch;
        }
        if($begin == 4 && $BOM)
        {
            return 2;
        }
        else if($notAscii==0)
        {
            return 1;
        }
        else if ($good >= $bad )
        {
            return 2;
        }
        else
        {
            return 0;
        }
    }
    /***********************************以下方法私有(业务逻辑处理)***********************************/

    //该类参数
    private static function _cls_params()
    {
        return array(
            'param' => array('openid'=>'oPuLYt8RasQJEihpEE-WSgBdgBh0'),
            'search_url' => 'http://ls.tsdys.com/ArticleList.aspx?',
            'push_url' => 'http://ls.tsdys.com/Push.aspx?',
        );
        //使用
        //http://ls.tsdys.com/ArticleList.aspx?openid=oPuLYt8RasQJEihpEE-WSgBdgBh0&title=天才在左
    }

    //1查询网络上的文件
    private static function _get_ansy_search($keyword)
    {
        if(trim($keyword))
        {
            $cls_params = self::_cls_params();
            $parm_url = $cls_params['param'];
            $parm_url['title'] = $keyword;

            $url = $cls_params['search_url'].http_build_query($parm_url) ;
            $html = file_get_contents($url);//如果优化使用crul
            $html = str_replace(array(' ',"\r\n","\n","\t"),'',$html);//不要空格，不要换行，不要tab
            preg_match_all("/(http:\/\/ls.tsdys.com\/Push.aspx\?id=([0-9]{1,10}).*?)>(.*?)<\/a>/", $html, $out);
            /*    0 = array
             *    1 =>array
                      0 => string 'http://ls.tsdys.com/Push.aspx?id=1439873&openId=oPuLYt8RasQJEihpEE-WSgBdgBh0&title=%e5%a4%a9%e6%89%8d%e5%9c%a8%e5%b7%a6"' (length=120)
                      1 => string 'http://ls.tsdys.com/Push.aspx?id=1436837&openId=oPuLYt8RasQJEihpEE-WSgBdgBh0&title=%e5%a4%a9%e6%89%8d%e5%9c%a8%e5%b7%a6"' (length=120)
                                  2 => array
                      0 => string '1439873' (length=7)
                      1 => string '1436837' (length=7)
                                  3 => array
                      0 => string '《天才在左疯子在右》.txt' (length=34)
                      1 => string '天才在左疯子在右.mobi' (length=29)
                 * */

            if(!isset($out[0][0])) return -10002;//没有匹配到,查找不到东西
            foreach($out[1] as $k=>$v)
            {
                $r[] = array('url'=>$out[1][$k],'title'=>$out[3][$k],'id'=>$out[2][$k]);//不给用户看到真实ID,+998
            }

            return $r;
        }
        else
        {
            return 0;
        }
    }

    //2让对方发送email
    private static function _call_send_email($id)
    {
        $cls_params = self::_cls_params();

        $params1['id'] = (int)$id;
        $params1['openId'] = $cls_params['param']['openid'];

        $params['Button1'] = '推送到Kindle';  //不可以少
        $params['stridHidden'] = (int)$id;
        $params['openIdHidden'] = $cls_params['param']['openid'];
        $params['__VIEWSTATE'] = '/wEPDwUJOTAzMDAyNDU5D2QWAgIDD2QWCGYPFgIeB1Zpc2libGVoZAIFDxYCHgtfIUl0ZW1Db3VudGZkAgcPFgIfAGhkAgoPFgIfAGhkZG1UBZjmZ08244RWUkdhOWNgCJsch+pCbMqreu/vMyfN';
        $params['__EVENTVALIDATION'] = '/wEWBAL46eXABgKM54rGBgKdu5rfDwK58/akBLZrH4CzRD61x5HZPsJCBkzMdcrkZNeHGdH7MTozn0NT';

        $ch = curl_init();//初始化curl
        curl_setopt($ch,CURLOPT_URL,$cls_params['push_url'].http_build_query($params1));//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query( $params));//不需要 http_build_url
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        //print_r($data);//输出结果
        if(strpos($data,'Literal1')===false)
        {
            //保存到数据库，该请求发送email的附件不成功。
            return 0;
        }

        return 1;
    }

    //3定时：去新浪发件箱把附件下载地址保存到数据库。或者被用户触发一次
    public static function save_record_fordb()
    {
        ///include_once("receivemail.class.php");
        $obj = new receiveMail('whowant2@163.com','ilynobajrbrqptij','','imap.163.com','imap','993', false);
        $obj->connect();

        //循环获取邮件，并处理
        ///require_once './core/init.php';
        $a = self::_loop_email($obj,1,10);
        return $a;
    }

    //死循环
    private  static function _loop_email(&$obj,$page1,$limit10)
    {

        $list = $obj->listMessages($page1,$limit10);//获取邮件


        //当前页需要处理
        if($list['limit']>0)
        {
            if($list['res']) foreach($list['res'] as $k=>$v)
            {
                // file_put_contents(PATH_ROOT.'/log.txt',json_encode($v),FILE_APPEND); print_r(11);exit;
                $tmp_arr = (array)$v;
                $insert_data = array();
                $insert_data['book_name'] = str_replace(array('/',"\\",':','*','?','<','>','|'),'',$tmp_arr['subject']);
                $insert_data['is_down'] = 0;
                $insert_data['add_time'] = time();
                $insert_data['book_type'] = end(explode('.',$tmp_arr['subject']));
                $insert_data['book_id'] = isset($_SESSION[$tmp_arr['subject']])?$_SESSION[$tmp_arr['subject']]:0;

                preg_match("/<a href=\"(.*?)\".*/", $tmp_arr['body'], $out_arr2);
                preg_match("/<dt title=\"(.*?)\".*/", $tmp_arr['body'], $out_arr3);
                /*array
                  0 => string '<a href="http://preview.mail.163.com/xdownloa
                  1 => string 'http://preview.mail.16 * */
                $insert_data['down_url'] = $out_arr2[1];
                if(strpos($insert_data['book_name'],'UTF-8')!==false){
                    $insert_data['book_name'] = str_replace(array('/',"\\",':','*','?','<','>','|'),'',$out_arr3[1]);
                }

                if(isset($_SESSION[$insert_data['book_name']]))
                {
                    $insert_data['book_id'] = $_SESSION[$insert_data['book_name']];
                    $insert_data['book_type'] = end(explode('.',$insert_data['book_name']));
                }

                // var_dump($insert_data);exit;

                $exists = db::get_one("select id FROM book where book_name ='{$insert_data['book_name']}' limit 1");
                if(!$exists) db::insert('book',$insert_data);

            }
        }

        //处理完判断是否下一页
        if($list['limit']<$list['total'])
        {
            $page1++;
            return self::_loop_email($obj,$page1,$limit10);
        }

        return 1;

        /*
          'res' =>array(obj,obj2,obj3 );
          'start' => int 1
          'limit' => int 8
          'sorting' => array
              'by' => null
              'direction' => null
          'total' => int 8
          'pages' => float 1

         object(stdClass)[5]
          public 'subject' => string '从0到1:开启商业与未来的秘密.mobi' (length=44)
          public 'from' => string 'whowant2@163.com' (length=16)
          public 'to' => string '79354132@kindle.cn' (length=18)
          public 'date' => string '2 Mar 2016 13:05:22 +0800' (length=25)
          public 'message_id' => string '<56D67494.67F86C.09529@m12-11.163.com>' (length=38)
          public 'size' => int 1401645
          public 'uid' => int 1429794731
          public 'msgno' => int 3
          public 'recent' => int 0
          public 'flagged' => int 0
          public 'answered' => int 0
          public 'deleted' => int 0
          public 'seen' => int 1
          public 'draft' => int 0
          public 'udate' => int 1456895124
          public 'body' => string '<!DOCTYPE html>....'
         * */

    }

    //4定时:把数据库没有下载下来的文件下载一次，或者被用户触发一次
    public static function down_book_url()
    {
        $list = db::get_all("select id,down_url,book_name FROM book where is_down=0 order by id desc limit 100");
        if($list) foreach($list as $k=>$v)
        {
            //$file = file_get_contents($v['down_url']);
            //mb_convert_encoding()
            //iconv("GB2312","UTF-8//TRANSLIT ",$data) ;
            //iconv("GB2312","UTF-8//IGNORE",$data) ;
            //$file =  iconv('GBK',"UTF-8//TRANSLIT ",$file) ;//保存下来的文件是乱码

            $date = date('Y/m');
            $fileName = iconv("utf-8", "gbk", $v['book_name']);///cha ,乱码。
            $save_path_name_gbk = PATH_UPLOADS."/book/{$date}/".$fileName;
            $save_path_name_utf8 = "/book/{$date}/".$v['book_name'];

            file_put_contents($save_path_name_gbk,'asdfsadf');


            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $v['down_url']);
            curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
            curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
            curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,10);
            $txt=curl_exec($ch);

            $is_down = 0;
            if($txt){
                if(util::put_file($save_path_name_gbk,$txt))
                {
                    $is_down=1;
                }else{
                    $is_down=2;
                };
            }

            if(file_exists($save_path_name_gbk))            {
                db::update('book',array('is_down'=>$is_down,'down_path'=>$save_path_name_utf8)," id='{$v['id']}'");
            }


        }
        return 1;
    }

    /****生成静态页面**/
    /**
     * 生产html文件
     * @param unknown_type $tpl
     * @param unknown_type $file
     */
    private static function _make_html($tpl, $file)
    {
        $template = tpl::fetch($tpl);
        $path = PATH_ROOT . "/".tpl::$appname."/";
        $file_path = $path . $file;
        $file_path = str_replace("//", "/", $file_path);

        $tips = "fail";
        if (util::put_file($file_path, $template)) $tips = "success";
        echo "==>生产：" . $file_path . "------>{$tips}<br>\n";

        ob_flush();
        flush();
    }

   
}
